package com.yl.ydk.presenter.impl

import android.content.Context
import android.content.Intent
import androidx.recyclerview.widget.GridLayoutManager
import com.yl.ydk.R
import com.yl.ydk.api.Api
import com.yl.ydk.base.BasePresenter
import com.yl.ydk.bean.VideoListBean
import com.yl.ydk.presenter.contract.HealthyVideoLisetFragmentContract
import com.yl.ydk.ui.activity.HealthyVideoHomeActivity
import com.yl.ydk.ui.activity.VideoPlayActivity
import com.yl.ydk.ui.adapter.HealthyVideoAdapter
import com.google.gson.Gson
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

class HealthyVideoLisetFragmentImpl : BasePresenter<HealthyVideoLisetFragmentContract.View>(),
    HealthyVideoLisetFragmentContract.Presenter<HealthyVideoLisetFragmentContract.View> {

    private var adapter: HealthyVideoAdapter? = null

    override fun getVideoList(context: Context, vararg query: String?) {
        showLoadingDialog(context)
        addSubscrebe(
            Api.getInstance()?.getVideoList(*query)
                ?.observeOn(AndroidSchedulers.mainThread())
                ?.subscribeOn(Schedulers.io())
                ?.unsubscribeOn(Schedulers.io())
                ?.subscribe(object : Observer<VideoListBean?> {
                    override fun onCompleted() {}
                    override fun onError(e: Throwable) {
                        dismissLoadingDialog()
                        mView?.showError(e.toString())
                    }

                    override fun onNext(t: VideoListBean?) {
                        dismissLoadingDialog()
                        if (t?.data != null && t.code == 200) {
                            adapter = HealthyVideoAdapter(t.data.list.toMutableList())
                            val manager = GridLayoutManager(context, 3)
                            mView?.getRecyclerView()?.let {
                                it.adapter = adapter
                                it.layoutManager = manager
                            }

                            adapter?.onListItemClick(object : HealthyVideoAdapter.onListItemClick {
                                override fun onListItemClick(item: VideoListBean.Data.DataX?) {
                                    HealthyVideoHomeActivity.healthyVideoHomeActivity?.let {
                                        val intent = Intent(it, VideoPlayActivity::class.java)
                                        intent.putExtra("data", Gson().toJson(item))
                                        it.startActivityIn(intent, it)
                                    }
                                }
                            })
                        } else {
                            mView?.showError(context.getString(R.string.connectFailure))
                        }
                    }
                })
        )
    }


}